package com.suxin.ratelimit.properties;

import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Value;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author Tang
 * @classname RateLimiterProperties
 * @description [  ]
 * @date 2021/7/13 23:04
 */
@Data
//@ConfigurationProperties(prefix = RateLimiterProperties.PREFIX)
public class RateLimiterProperties {

    public static final String PREFIX = "gateway.ratelimit";

    @Value("${spring.application.name}")
    private String keyPrefix;
    private Map<String, Policy> polices = new HashMap<>();

    private boolean enable;
    private Policy defaultPolicy;
    /**
     * 存储策略
     */
    private Repository repository = Repository.IN_MEMORY;

    public Optional<Policy> getPolicy(String key) {
        return Optional.ofNullable(polices.getOrDefault(key, defaultPolicy));
    }

    public enum Repository{
        REDIS,JPA, IN_MEMORY;
    }

    @Data
    @NoArgsConstructor
    public static class Policy {
        private Long refreshInterval = TimeUnit.MINUTES.toSeconds(1L);
        private Long limit;
        private List<Type> types = new ArrayList<>();

        public enum Type{
            ORIGIN,USER,URL;
        }
    }
}